package com.gzdh.tang.mobile.interceptor;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPayConstants;
import com.gzdh.tang.comm.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static com.gzdh.tang.config.weixin.WXPayUtil.HMACSHA256;

@Component
public class SignInterceptor implements HandlerInterceptor {

    @Autowired
    private Environment environment;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        Map<String, String> map = new HashMap<>();
        Map<String, String[]> reqMap = request.getParameterMap();
        reqMap.forEach((t, u) -> {
//            System.out.println(t + "->>>" + u[0]);
            map.put(t, u[0]);
        });
        String sign = request.getParameter("sign");
        response.setContentType("text/html;charset=utf-8");
        if (sign == null) {
            response.setStatus(403);
            response.getWriter().print(JSON.toJSON(new Result<>("签名验证失败", 403, null)));
            return false;
        }
        if (!isSignatureValid(map, "123456789987654321")) {
            response.setStatus(403);
            response.getWriter().print(JSON.toJSON(new Result<>("签名验证失败", 403, null)));
            return false;
        }
        String times = request.getParameter("urlTime");
        Long sysTime = System.currentTimeMillis();
        if (sysTime - Long.valueOf(times) > 10000) {
            response.setStatus(403);
            response.getWriter().print(JSON.toJSON(new Result<>("签名验证失败", 403, null)));
            return false;
        }
        System.out.println("拦截器放行");

        return true;
    }

    public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
        if (!data.containsKey(WXPayConstants.FIELD_SIGN)) {
            return false;
        }
        String sign = data.get(WXPayConstants.FIELD_SIGN);
        return generateSignature(data, key).equals(sign);
    }

    public static String generateSignature(final Map<String, String> data, String key) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(WXPayConstants.FIELD_SIGN)) {
                continue;
            }
            if (data.get(k).trim().length() > 0) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
        }
        sb.append("key=").append(key);
        return HMACSHA256(sb.toString(), key);
    }
}
